<template>
    <div>
        <!-- 面包屑导航区 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图 -->
        <el-card>
            <!-- 添加角色按钮区 -->
            <el-row>
                <el-col>
                    <el-button type="primary" @click="addRolesVisible = true">添加角色</el-button>
                </el-col>
            </el-row>
            <!-- 角色列表区 -->
            <el-table :data="RolesList"
                      style="width: 100%"
                      border
                      stripe>
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <el-row :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']" v-for="(item1, i1) in scope.row.children" :key="item1.id">
                            <!-- 渲染一级权限 -->
                            <el-col :span="5">
                                <el-tag>
                                    {{item1.authName}}
                                </el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 渲染二级和三级权限 -->
                            <el-col :span="19">
                                <el-row v-for="(item2) in item1.children" :key="item2.id" :class="['vcenter']">
                                    <el-col :span="6">
                                        <el-tag type="success" >
                                            {{item2.authName}}
                                        </el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18" >
                                        <el-tag type="warning" v-for="item3 in item2.children" :key="item3.id" closable @close="removeRightById(scope.row,item3.id)">
                                            {{item3.authName}}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
              <el-table-column type="index">
              </el-table-column>
              <el-table-column label="角色名称" prop="roleName">
              </el-table-column>
               <el-table-column label="描述" prop="roleDesc">
              </el-table-column>
              <el-table-column label="操作">
                  <template slot-scope="scope">
                      <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEdit(scope.row.id)">编辑</el-button>
                      <el-button type="danger" icon="el-icon-delete" size="mini" @click="delRole(scope.row.id)" >删除</el-button>
                      <el-button type="warning" icon="el-icon-setting" size="mini" @click="shouSetRightDialog(scope.row)">分配权限</el-button>
                  </template>
              </el-table-column>
            </el-table>
        </el-card>
             <!-- 添加角色对话框 -->
            <el-dialog
                title="添加角色"
                :visible.sync="addRolesVisible"
                width="50%"
                @close="addRolesClose"
                >
                <!-- 内容主题区 -->
                <el-form :model="addRolesForm" :rules="addRolesRules" ref="addRolesRef" label-width="80px" :status-icon="true">
                    <el-form-item label="角色名称" prop="roleName">
                      <el-input v-model="addRolesForm.roleName"></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述" prop="roleDesc">
                      <el-input v-model="addRolesForm.roleDesc"></el-input>
                    </el-form-item>
                </el-form>
                <!-- 底部按钮区域 -->
                <span slot="footer" class="dialog-footer">
                  <el-button @click="addRolesClose">取 消</el-button>
                  <el-button type="primary" @click="addRoles">确 定</el-button>
                </span>
            </el-dialog>
             <!-- 修改角色对话框 -->
            <el-dialog
                title="修改角色"
                :visible.sync="editRolesVisible"
                width="50%"
                @close="editDialogClose"
                >
                <!-- 内容主题区 -->
                <el-form :model="editRolesForm" :rules="editRolesRules" ref="editRolesRef" label-width="80px" :status-icon="true">
                    <el-form-item label="角色名称" prop="roleName">
                      <el-input v-model="editRolesForm.roleName"></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述" prop="roleDesc">
                      <el-input v-model="editRolesForm.roleDesc"></el-input>
                    </el-form-item>
                </el-form>
                <!-- 底部按钮区域 -->
                <span slot="footer" class="dialog-footer">
                  <el-button @click="editDialogClose">取 消</el-button>
                  <el-button type="primary" @click="editRoles">确 定</el-button>
                </span>
            </el-dialog>
            <!-- 分配权限对话框 -->
            <el-dialog
              title="分配权限"
              :visible.sync="setRightDialogVisible"
              width="50%"
              @close="treeClose">
              <!-- 树形控件 -->
              <el-tree :data="rightList"
              :props="rightListProps"
              show-checkbox
              node-key="id"
              :default-expand-all="true"
              :default-checked-keys="defKeys"
              ref="treeRef"
              ></el-tree>
              <span slot="footer" class="dialog-footer">
                <el-button @click="setRightDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRights">确 定</el-button>
              </span>
            </el-dialog>
        </div>
</template>
<script>
export default {
    data() {
        return {
            RolesList: [],
            addRolesVisible: false,
            editRolesVisible: false,
            addRolesForm: {
                roleName: '',
                roleDesc: ''
            },
            editRolesForm: {
                roleName: '',
                roleDesc: '',
                roleId: ''
            },
            addRolesRules: {
                 rolesName: [
                      { required: true, message: '请输入角色名称', trigger: 'blur' }
                ],
                rolesDescribe: [
                     { required: true, message: '请输入角色描述', trigger: 'blur' }
                ]
            },
            editRolesRules: {
                 rolesName: [
                      { required: true, message: '请输入角色名称', trigger: 'blur' }
                ],
                rolesDescribe: [
                     { required: true, message: '请输入角色描述', trigger: 'blur' }
                ]
            },
            // 控制分配权限对话框的显示与隐藏
            setRightDialogVisible: false,
            // 用户权限数据
            rightList: [],
            rightListProps: {
                children: 'children',
                label: 'authName'
            },
            // 默认选中的节点id值数组
            defKeys: [],
            roleId: ''
        }
    },
    created() {
        this.getRolesList()
    },
    methods: {
        // 获取角色列表
        async getRolesList() {
            const { data: res } = await this.$http.get(`roles`)
            if (res.meta.status !== 200) {
               return this.$message.error('获取角色列表失败')
            }
            this.RolesList = res.data
        },
        // 发送添加角色请求
        addRoles() {
               this.$refs.addRolesRef.validate(async valid => {
                if (!valid) return
                const { data: res } = await this.$http.post(`roles`, this.addRolesForm)
                if (res.meta.status !== 201) {
                    this.$message.error('添加角色失败')
                }
                this.$message.success('添加角色成功')
                this.addRolesVisible = false
                // 刷新用户列表
                this.getRolesList()
            })
        },
        // 添加角色框关闭后清空数据
        addRolesClose() {
            this.$refs.addRolesRef.resetFields()
            this.addRolesVisible = false
        },
        // 删除角色功能
        async delRole(id) {
        const result = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
         .catch(err => err)
         if (result !== 'confirm') {
            return this.$message.info('已取消删除')
        }
        const { data: res } = await this.$http.delete(`roles/` + id)
        if (res.meta.status !== 200) {
           return this.$message.error('删除角色失败')
        }
        this.$message.success('删除角色成功')
        this.getRolesList()
        },
        // 关闭修改表单后清空数据
        editDialogClose() {
            this.$refs.editRolesRef.resetFields()
            this.editRolesVisible = false
        },
        // 显示修改用户框
         async showEdit(id) {
            const { data: res } = await this.$http.get(`roles/` + id)
           if (res.meta.status !== 200) {
              return this.$message.error('查询角色信息失败')
           }
           this.editRolesForm = res.data
           this.editRolesVisible = true
        },
        // 提交修改角色信息请求
        editRoles() {
            this.$refs.editRolesRef.validate(async valid => {
                if (!valid) {
                    return
                }
            const { data: res } = await this.$http.put(`roles/` + this.editRolesForm.roleId, {
                roleName: this.editRolesForm.roleName,
                roleDesc: this.editRolesForm.roleDesc
            })
            if (res.meta.status !== 200) {
               return this.$message.error('修改角色失败')
            }
            this.editRolesVisible = false
            this.getRolesList()
            this.$message.success('修改角色成功')
            })
        },
        // 根据id删除权限
        async removeRightById(role, rightId) {
            // 弹框提示是否删除
            const result = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
         .catch(err => err)
         if (result !== 'confirm') {
            return this.$message.info('已取消删除')
        }
        const { data: res } = await this.$http.delete(`roles/` + role.id + `/rights/` + rightId)
        if (res.meta.status !== 200) {
            return this.$message.error('删除角色权限失败')
        }
        role.children = res.data
        },
        // 展示树形列表
        async shouSetRightDialog(role) {
            this.roleId = role.id
            // 获取权限数据
            const { data: res } = await this.$http.get(`rights/tree`)
            if (res.meta.status !== 200) {
                this.$message.error('获取用户权限失败')
            }
            this.rightList = res.data
            this.getLeafKeys(role, this.defKeys)
            this.setRightDialogVisible = true
        },
        // 通过递归的形式获取角色下所有三级权限的id并保存到defkays数组中
        getLeafKeys(node, arr) {
            if (!node.children) {
                return arr.push(node.id)
            }
            node.children.forEach(item => {
                this.getLeafKeys(item, arr)
            })
        },
        // 重置数据
        treeClose() {
            this.defKeys = []
        },
        // 分配用户权限请求
        async allotRights() {
            const keys = [
                ...this.$refs.treeRef.getCheckedKeys(),
                ...this.$refs.treeRef.getHalfCheckedKeys()
            ]
            const keyStr = keys.join(',')
            const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, {
                rids: keyStr
            })
            if (res.meta.status !== 200) {
              return this.$message.eror('分配用户权限失败')
            }
                this.$message.success('分配用户权限成功')
                this.setRightDialogVisible = false
                this.getRolesList()
        }
    }
}
</script>
<style lang="less" scoped>
    .el-tag {
        margin: 7px
    }
    .bdtop{
        border-top: 1px solid #eee
    }
    .bdbottom{
        border-bottom: 1px solid #eee
    }
    .vcenter {
        display: flex;
        align-items: center;
    }
</style>